package JUC.第02章_Future;

import java.util.concurrent.*;

/**
 * CompletableFuture  继承的接口 有 Future和 CompletionStage
 */
public class D3_CompletionStageAPI值得获取 {
    public static void main(String[] args) {

        CompletableFuture<Integer> cf = CompletableFuture.supplyAsync(() -> {
            int result = ThreadLocalRandom.current().nextInt(10);//随机获取[0-9]
            try { TimeUnit.MILLISECONDS.sleep(2000); } catch (Exception e) { e.printStackTrace(); }
            return result;
        });
        //当运算还没出结果的时候 会返回100 否则返回运算结果的值
        System.out.println(cf.getNow(100));

        //是否打断计算  true 打断了结果会成为我给的值 50    false 已经计算完毕返回真实值
        System.out.println(cf.complete(50));
        System.out.println(cf.join());
        System.out.println("--------------------------------");

        cf = CompletableFuture.supplyAsync(() -> {
            int result = ThreadLocalRandom.current().nextInt(10);//随机获取[0-9]
            try { TimeUnit.MILLISECONDS.sleep(2000); } catch (Exception e) { e.printStackTrace(); }
            return result;
        });
        try {
            System.out.println(cf.get(1L, TimeUnit.SECONDS));//获取指定时间内结果否则报错
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            System.out.println(cf.get());//一直等待获取结果
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(cf.join());//和get区别是   他不抛异常
    }
}
